# Create your views here.
import datetime
import random

from rest_framework.decorators import action
from rest_framework.viewsets import ModelViewSet
from django_redis import get_redis_connection

from apps.bottles.models import Bottle
from apps.bottles.serializers import BottleModelSerializer
from apps.users.models import User
from apps.users.serializers import UserModelSerializer
from common.redis_constants import DRIFT_BOTTLE_LIKES_PREFIX
from common.result import fail, success
from common.utils import require_login
from config.settings import PROJECT_CACHE_NAME


class BottleModelViewSet(ModelViewSet):
    def get_queryset(self):
        return Bottle.objects.filter(is_deleted=False)

    def get_serializer_class(self):
        return BottleModelSerializer

    def list(self, request, *args, **kwargs):
        """
        漂流瓶列表， 这里可以设计特殊的算法实现个性化推荐
        """
        # bottles = self.get_queryset().filter(is_flowing=1)
        # serializer = BottleModelSerializer(bottles, many=True)
        # data = serializer.data
        # random.shuffle(data)
        # data[0]["isLiked"] = True
        # return success(None, data[0])

        bottles = self.get_queryset().filter(is_flowing=1)
        if len(bottles) == 0:
            return success(None, None)
        serializer = BottleModelSerializer(bottles, many=True)
        data = serializer.data
        random.shuffle(data)
        bottle_id = data[0].get("id")
        # 修改持有人， 漂流状态
        instance = Bottle.objects.get(id=bottle_id)
        instance.owner_id = request.user.id
        instance.is_flowing = Bottle.FLOWING_STATUS_ENUM.get("NOT_FLOWING")
        instance.save()
        serializer = self.get_serializer(instance)
        data = serializer.data

        # 查询该用户是否已经点赞该漂流瓶
        conn = get_redis_connection(PROJECT_CACHE_NAME)
        key = DRIFT_BOTTLE_LIKES_PREFIX + bottle_id.__str__()
        score = conn.zscore(key, request.user.id.__str__())
        if score:
            data["isLike"] = True
        else:
            data["isLiked"] = False
        return success(None, data)

    @require_login
    def create(self, request, *args, **kwargs):
        # title = request.data.get("title")
        # content = request.data.get("content")
        # if not title or not content:
        #     return fail("漂流瓶创建失败！")
        # data = {
        #     "title": title,
        #     "content": content,
        #     "owner_id": request.user.id,
        #     "create_user_id": request.user.id,
        #     "update_user_id": request.user.id
        # }
        # serializer = self.get_serializer(data=data)
        # serializer.is_valid(raise_exception=True)
        # serializer.save()
        # return success("创建成功！", serializer.data)

        title = request.data.get("title")
        content = request.data.get("content")
        if not title or not content:
            return fail("漂流瓶创建失败！")
        data = {
            "title": title,
            "content": content,
            "create_user_id": request.user.id,
            "update_user_id": request.user.id,
            "is_flowing": Bottle.FLOWING_STATUS_ENUM.get("FLOWING")
        }
        serializer = self.get_serializer(data=data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return success("创建成功！", serializer.data)

    @require_login
    def destroy(self, request, *args, **kwargs):
        """
        删除漂流瓶
        """
        instance = self.get_object()
        if instance.owner_id != request.user.id:
            return fail("该漂流瓶不属于您！")
        instance.delete()
        return success("删除成功！")

    @require_login
    def update(self, request, *args, **kwargs):
        """
        更新漂流瓶
        """
        instance = self.get_object()
        if instance.owner_id != request.user.id:
            return fail("该漂流瓶不属于您！")
        data = {}
        title = request.data.get("title")
        if title:
            data["title"] = title
        content = request.data.get("content")
        if content:
            data["content"] = content
        serializer = self.get_serializer(instance, data=data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return success("更新成功！")

    def retrieve(self, request, *args, **kwargs):
        """
        获取漂流瓶详情，并将查看次数加一
        """
        instance = self.get_object()
        instance.views += 1
        instance.save()
        return success("ok", self.get_serializer(instance).data)

    @action(methods=["post"], detail=True, url_path="send")
    def send_bottle(self, request, pk):
        """
        发送漂流瓶
        """
        # instance = self.get_object()
        # if not request.user.id:
        #     return fail("请先登录！")
        # if instance.owner_id != request.user.id:
        #     return fail("该漂流瓶不属于您！")
        # instance.pre_owner_id = instance.owner_id
        # instance.owner_id = None
        # instance.is_flowing = Bottle.FLOWING_STATUS_ENUM.get("FLOWING")
        # instance.save()
        # return success("发送成功！")

        instance = self.get_object()
        if not request.user.id:
            return fail("请先登录！")
        if instance.owner_id != request.user.id:
            return fail("该漂流瓶不属于您！")
        instance.owner_id = None
        instance.is_flowing = Bottle.FLOWING_STATUS_ENUM.get("FLOWING")
        instance.save()
        return success("发送成功！")

    @action(methods=["post"], detail=True, url_path="collect")
    def collect_bottle(self, request, pk):
        """
        拾取漂流瓶
        """
        instance = self.get_object()
        if not request.user.id:
            return fail("请先登录！")
        if instance.owner_id:
            return fail("你无法拾取该漂流瓶！")
        instance.owner_id = request.user.id
        instance.is_flowing = Bottle.FLOWING_STATUS_ENUM.get("NOT_FLOWING")
        return success("拾取成功！")

    @action(methods=["post"], detail=True, url_path="like")
    def like(self, request, pk):
        """
        点赞获取取消点赞
        """
        if not request.user.id:
            return fail("请先登录！")   # 重定向到login
        instance = self.get_object()
        if not instance.is_flowing:
            return fail("只有漂流中的瓶子才能点赞")
        key = DRIFT_BOTTLE_LIKES_PREFIX + instance.id.__str__()
        conn = get_redis_connection(PROJECT_CACHE_NAME)
        # 查询用户是否点赞
        score = conn.zscore(key, request.user.id.__str__())
        if score:
            conn.zrem(key, request.user.id.__str__())
            instance.likes -= 1
        else:
            data = {request.user.id.__str__(): datetime.datetime.now().timestamp()}
            conn.zadd(key, data)
            instance.likes += 1
        instance.save()
        return success("ok")

    @action(methods=["get"], detail=True, url_path="top5")
    def top5(self, request, pk):
        """
        获取点赞前五位用户信息
        """
        instance = self.get_object()
        key = DRIFT_BOTTLE_LIKES_PREFIX + instance.id.__str__()
        conn = get_redis_connection(PROJECT_CACHE_NAME)
        ids = conn.zrevrange(key, 0, 5)
        if not ids:
            return success("ok", [])
        users = []
        for i in ids:
            users.append(User.objects.get(id=i.decode()))
        users.reverse()
        serializer = UserModelSerializer(users, many=True)
        return success("ok", serializer.data)
